package cn.pud.rpademo01;

/**
 * @Author: Miyako
 * @Date: 2024-11-11-15:12
 * @Description:
 */
import javax.mail.*;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import java.io.*;
import java.nio.file.Files;
import java.util.*;

import com.sun.mail.imap.IMAPStore;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

public class RPAEmailExcelDemo {


    /**
     * @param: [args]
     * @return: void
     * @description: 使用imap协议获取 网易邮箱中收件箱中的所有邮件,并筛选出其中含有Excl的文件 将其保存到本地
     **/
    public static void main(String[] args) {
        // 邮件服务器配置
        String host = "imap.163.com";  // 邮件服务器
        String username = "miyakonano@163.com"; // 邮箱地址
        String password = ""; // （邮箱给第三方应用开通的授权码）

        try {
            //
            Properties properties = new Properties();
            properties.put("mail.store.protocol", "imap");
            Session emailSession = Session.getDefaultInstance(properties);

            HashMap IAM = new HashMap<>();
            IAM.put("name","Miyako");
            // 使用imap会话机制，连接服务器
            IMAPStore store = (IMAPStore) emailSession.getStore("imap");
            store.connect(host,username, password);
            //网易邮箱需要配置imap进行
            store.id(IAM);

            // 获取邮箱的“收件箱”文件夹
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_WRITE);

            // 获取邮件内容数组
            Message[] messages = folder.getMessages();
            System.out.println("Total messages: " + messages.length);

            // 遍历所有邮件
            for (Message message : messages) {
                System.out.println("Subject: " + message.getSubject());
                //判断邮件标题是否符合
                if (message.getSubject().startsWith("666"))
                //检测邮件内容是否含有附件,如果有附件(包含音视频文本文档都算)会返回MimeMultipart对象
                if (message.getContent() instanceof MimeMultipart) {
                    MimeMultipart multipart = (MimeMultipart) message.getContent();
                    //对筛选出的附件进行遍历
                    for (int i = 0; i < multipart.getCount(); i++) {
                        MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(i);
                        String fileName = part.getFileName();
                        if (fileName != null ) {
                            // 去附件中筛选出Excel文件
                            if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                                System.out.println("Found Excel file: " + fileName);
                                //下载附件
                                InputStream inputStream = part.getInputStream();
                                File savePath = new File("D:\\Excel\\"+fileName);
                                saveFile(inputStream,savePath);
                            }
                        }
                    }
                }
            }
            // 关闭文件夹和会话
            folder.close(false);
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 保存文件到本地
    public static void saveFile(InputStream inputStream, File file) throws IOException {
        try (BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                //以字符的方式写入（输出到）硬盘
                bos.write(buffer, 0, bytesRead);
            }
            System.out.println("save to: " + file.getAbsolutePath());
        }
    }

    // 读取并处理Excel文件
    public static void readExcelFile(File file) {
        try (FileInputStream fis = new FileInputStream(file);
             XSSFWorkbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheetAt(0);  // 获取第一个工作表
            System.out.println("Reading Excel file: " + file.getName());

            // 遍历工作表的每一行和每一列
            for (Row row : sheet) {
                for (Cell cell : row) {
                    switch (cell.getCellType()) {
                        case STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "\t");
                            break;
                        case BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        default:
                            System.out.print("Unknown Type\t");
                    }
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
